package com.rimi.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rimi.bean.User;
import com.rimi.cache.SelectCache;
import com.rimi.service.LoginService;
import com.rimi.service.UserService;
import com.rimi.util.PhoneUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.support.json.JSONUtils;
import com.rimi.errorcode.LuoErrorCode;
import com.rimi.exception.BusinessException;
import com.rimi.util.DecriptUtil;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private UserService userService;

    @Autowired
    private SelectCache selectCache;

    @RequestMapping("/index.jhtml")
    public ModelAndView getIndex(HttpServletRequest request) throws Exception {
        ModelAndView mav = new ModelAndView("index");
        return mav;
    }

    @RequestMapping("/exceptionForPageJumps.jhtml")
    public ModelAndView exceptionForPageJumps(HttpServletRequest request) throws Exception {
        throw new BusinessException(LuoErrorCode.NULL_OBJ);
    }

    @RequestMapping(value="/businessException.json", method=RequestMethod.POST)
    @ResponseBody
    public String businessException(HttpServletRequest request) {
        throw new BusinessException(LuoErrorCode.NULL_OBJ);
    }

    @RequestMapping(value="/otherException.json", method=RequestMethod.POST)
    @ResponseBody
    public String otherException(HttpServletRequest request) throws Exception {
        throw new Exception();
    }

    //跳转到登录页面
    @RequestMapping("/login.jhtml")
    public ModelAndView login() throws Exception {
        ModelAndView mav = new ModelAndView("login");
        return mav;
    }

    //跳转到登录成功页面
    @RequestMapping("/loginsuccess.jhtml")
    public ModelAndView loginsuccess() throws Exception {
        ModelAndView mav = new ModelAndView("redirect:/select/index");
        return mav;
    }

    /**
     * 验证用户名和密码
     * @param  username,String password
     * @return
     */
    @RequestMapping(value="/checkLogin.jhtml",method=RequestMethod.POST)
    @ResponseBody
    public String checkLogin(String username, String password ,HttpServletRequest request) {
        Map<String, Object> result = new HashMap<String, Object>();
        try{
            UsernamePasswordToken token = new UsernamePasswordToken(username, DecriptUtil.MD5(password));
            Subject currentUser = SecurityUtils.getSubject();
            if (!currentUser.isAuthenticated()){
                //使用shiro来验证
                token.setRememberMe(false);//设置记住用户
                currentUser.login(token);//验证角色和权限
                User user =null;
                System.out.println((String) currentUser.getPrincipal());
                user = loginService.getUserByName((String) currentUser.getPrincipal());
                if(user==null){
                    user = loginService.getUserByPhone((String) currentUser.getPrincipal());
                }
                request.getSession().setAttribute("user",user);
            }
        }catch(Exception ex){
            ex.printStackTrace();
            throw new BusinessException(LuoErrorCode.LOGIN_VERIFY_FAILURE);
        }
        result.put("success", true);
        return JSONUtils.toJSONString(result);
    }

    /**
     * 退出登录
     */
    @RequestMapping(value="/logout.json",method=RequestMethod.POST)
    @ResponseBody
    public String logout() {
        System.out.println(5);
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("success", true);
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return JSONUtils.toJSONString(result);
    }

    @RequestMapping(value="/register",method=RequestMethod.POST)
    @ResponseBody
    public void addUser(HttpServletRequest request, HttpServletResponse response) {
        //获取参数
        String userName = request.getParameter("register-username");
        String phon = request.getParameter("register-phone");
        String code = request.getParameter("register-code");
        String password = request.getParameter("register-password");
        String isok = request.getParameter("isok");
        if("3".equals(isok)){
            User user = loginService.getUserByPhone(phon);
            User user2 = loginService.getUserByName(userName);
            if(user2==null && user==null){
                //响应
                String json = JSON.toJSONString("ok");
                try {
                    response.getWriter().write(json);
                    response.getWriter().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else if(user2!=null){
                //响应
                String json = JSON.toJSONString("no");
                try {
                    response.getWriter().write(json);
                    response.getWriter().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else{
                String json = JSON.toJSONString("pno");
                try {
                    response.getWriter().write(json);
                    response.getWriter().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if ("2".equals(isok)) {
            //6为数的随机验证码
            String str = new Random().nextInt(10) + "";
            for (int i = 0; i < 5; i++) {
                str += new Random().nextInt(10);
            }
            try {
                SendSmsResponse sendSmsResponse = PhoneUtil.sendSms(phon, str);
                HttpSession session = request.getSession();
                session.setMaxInactiveInterval(300);
                session.setAttribute("str", str);

                String json = JSON.toJSONString("ok");
                //响应
                response.getWriter().write(json);
                response.getWriter().close();
            } catch (ClientException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if ("1".equals(isok)) {
            String str = (String) request.getSession().getAttribute("str");
            if(str==null || "".equals(str)){
                String json = JSON.toJSONString("xiaoshi");
                //响应
                try {
                    response.getWriter().write(json);
                    response.getWriter().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (str.equals(code)) {
                User user = new User();
                user.setUserId(0);
                user.setUserName(userName);
                user.setUserPs(DecriptUtil.MD5(password));
                user.setUserPhone(phon);
                user.setUserHardUrl("/images/ghs.png");
                Date date = new Date();
                user.setUserAddtime(date);
                boolean flag = userService.insert(user);
                if (flag) {
                    String json = JSON.toJSONString("ok");
                    //响应
                    try {
                        response.getWriter().write(json);
                        response.getWriter().close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    String json = JSON.toJSONString("no");
                    //响应
                    try {
                        response.getWriter().write(json);
                        response.getWriter().close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } else {
                String json = JSON.toJSONString("cuowu");
                try {
                    response.getWriter().write(json);
                    response.getWriter().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    @RequestMapping(value="/forget",method=RequestMethod.POST)
    @ResponseBody
    public void forgetUser(HttpServletRequest request, HttpServletResponse response) {
        String phon = request.getParameter("phone");
        String code = request.getParameter("code");
        String password = request.getParameter("password");
        String isok = request.getParameter("isok");
        if("1".equals(isok)){
            User user = loginService.getUserByPhone(phon);
            if(user==null){
                String json = JSON.toJSONString("no");
                try {
                    response.getWriter().write(json);
                    response.getWriter().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else{
                String json = JSON.toJSONString("ok");
                try {
                    response.getWriter().write(json);
                    response.getWriter().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        if("2".equals(isok)){
            String str = new Random().nextInt(10) + "";
            for (int i = 0; i < 5; i++) {
                str += new Random().nextInt(10);
            }
            try {
                SendSmsResponse sendSmsResponse = PhoneUtil.sendSms2(phon, str);
                HttpSession session = request.getSession();
                session.setMaxInactiveInterval(300);
                session.setAttribute("str2", str);
                String json = JSON.toJSONString("ok");
                //响应
                response.getWriter().write(json);
                response.getWriter().close();
            } catch (ClientException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if("3".equals(isok)){
            String str = (String) request.getSession().getAttribute("str2");
            if(str==null || "".equals(str)){
                String json = JSON.toJSONString("xiaoshi");
                //响应
                try {
                    response.getWriter().write(json);
                    response.getWriter().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(str.equals(code)){
                User user = new User();
                user.setUserPs(DecriptUtil.MD5(password));
                boolean user_phone = userService.update(user, new EntityWrapper<User>().eq("user_phone", phon));
                selectCache.removeCacheList("user"+phon);
                if(user_phone){
                    String json = JSON.toJSONString("ok");
                    //响应
                    try {
                        response.getWriter().write(json);
                        response.getWriter().close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else{
                    String json = JSON.toJSONString("no");
                    //响应
                    try {
                        response.getWriter().write(json);
                        response.getWriter().close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }else{
                String json = JSON.toJSONString("cuowu");
                //响应
                try {
                    response.getWriter().write(json);
                    response.getWriter().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

}
